<template>
  <div class="actionMonitor">
    <el-row class="actionMonitor_nav">
      <el-col :span="24" class="titles">行为监控</el-col>
    </el-row>
    <el-row class="actionMonitorContent">
      <el-col :span="24" style="margin-bottom:20px">
        <el-col :span="24" class="top-btnModule">
          <el-button
            type="primary"
            icon="el-icon-upload2"
            @click="dialogFormVisible = true"
            v-show="showBtn"
          >上传数据</el-button>
          <el-button type="primary" @click="openApp" plain>启动应用</el-button>
        </el-col>
        <el-col :span="24" class="mid-tableModule">
          <el-col :span="12">
            <el-table
              :highlight-current-row="true"
              :data="actionTable.list"
              @row-click="getRowData"
              :header-cell-style="{background:'#f5f5f5'}"
            >
              <el-table-column
                align="center"
                prop="behavior_time"
                class="normal-column"
                :render-header="renderTimeHeader"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="camera_name"
                class="normal-column"
                :formatter="handleCameraFilter"
                :render-header="renderPointHeader"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="name"
                class="normal-column"
                :formatter="handleBehaviorFilter"
                :render-header="renderStateHeader"
              ></el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <div class="image-box">
              <img :src="pic_url" alt />
            </div>
          </el-col>
        </el-col>
        <el-col :span="24">
          <el-pagination
            @current-change="actionPageChange"
            :current-page="requestParams.page"
            :page-size="requestParams.page_size"
            :page-sizes="[5]"
            layout="total, sizes,prev, pager, next, jumper"
            :total="actionTable.total_count"
            align="center"
          ></el-pagination>
        </el-col>
        <el-dialog
          title="上传数据"
          :visible.sync="dialogFormVisible"
          class="upload-dialog"
          width="32%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
        >
          <el-form :model="form" ref="form" :rules="rules" label-width="100px">
            <el-form-item label="时间" prop="time">
              <el-date-picker
                v-model="form.time"
                @change="changeTime(form.time)"
                type="datetime"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="摄像机点位" prop="point">
              <el-select v-model="form.point" class="dialog-select" placeholder="请选择">
                <el-option
                  v-for="(item,index) in  pointList"
                  :label="item.camera_name"
                  :key="index"
                  :value="item.camera_id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="行为状态" prop="state">
              <el-select v-model="form.state" class="dialog-select" placeholder="请选择">
                <el-option
                  v-for="(item,index) in  stateList"
                  :label="item.name"
                  :key="index"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图像数据" prop="imageUrl">
              <el-upload
                class="upload-demo"
                action
                accept=".jpg, .png, .gif"
                :http-request="unitUpload"
                :before-remove="beforeRemove"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                multiple
                :on-exceed="handleExceed"
                :limit="1"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">图片小于2M,上传格式:JPG,PNG,GIF</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false,clearData('form')">取 消</el-button>
            <el-button type="primary" @click="submitData('form')">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>
// var reDateTime = /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/;
import { monitorPublicApi } from "@/services/ProjectCenter";
import { standardCodeApi } from "@/services/StandardCode";
export default {
  data() {
    var checkTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("时间不能为空"));
      } else if (
        !/^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/.test(
          value
        )
      ) {
        callback(new Error("时间格式不符，请重新输入"));
      } else {
        callback();
      }
    };
    var checkPoint = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择摄像机点位"));
      } else {
        callback();
      }
    };
    var checkState = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择点位状态"));
      } else {
        callback();
      }
    };
    var checkImage = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("上传的图片不能为空"));
      } else {
        callback();
      }
    };
    return {
      projects: this.$route.query.projects, //项目id集合
      requestParams: {
        page: 1,
        page_size: 10
      },
      actionTable: {
        list: [],
        total_count: 0
      },
      timeValue: "", //时间筛选的值
      pointValue: "", //点位筛选的值
      stateValue: "", //状态筛选的值
      filters: [],
      pointList: [],
      stateList: [],
      dialogFormVisible: false, //上传图像的弹窗
      form: {
        //上传图像弹窗的表单
        time: "",
        point: "",
        state: "",
        imageUrl: ""
      },
      upload_path: "", //上传图片的路径
      fileList: [],
      //表单规则校验
      rules: {
        time: [{ validator: checkTime, trigger: "change" }],
        point: [{ validator: checkPoint, trigger: "change" }],
        state: [{ validator: checkState, trigger: "change" }],
        imageUrl: [{ validator: checkImage, trigger: "blur" }]
      },
      options: [],
      pic_url: "", //右侧展示图片的地址,
      showBtn: ""
    };
  },
  methods: {
    //时间下拉框渲染
    renderTimeHeader(h) {
      //下拉框选项
      return h(
        "el-select",
        {
          //el-select实现下拉框
          style: "width:150px",
          class: "normal-top-select",
          on: {
            input: value => {
              //随着下拉框的不同，文字框里的内容改变
              this.timeValue = value;
              change: this.searchTime(); // 文字框里的内容 change事件
            }
          },
          props: {
            placeholder: "时间",
            value: this.timeValue //文字框的内容取决于这个value
          }
        },
        [
          //下拉框里面填充选项，通过map遍历filters，为每一个选项赋值。
          this.filters.map(item => {
            return h("el-option", {
              props: {
                value: item.value,
                label: item.name
              }
            });
          })
        ]
      );
    },
    //选择时间进行筛选事件，重新渲染表格
    searchTime() {
      this.getListData();
    },
    //摄像点位下拉框渲染
    renderPointHeader(h) {
      return h(
        "el-select",
        {
          //el-select实现下拉框
          style: "width:150px",
          class: "normal-top-select",
          on: {
            input: value => {
              //随着下拉框的不同，文字框里的内容改变
              this.pointValue = value;
              change: this.searchPoint(); // 文字框里的内容 change事件
            }
          },
          props: {
            placeholder: "摄像点位",
            value: this.pointValue //文字框的内容取决于这个value
          }
        },
        [
          //下拉框里面填充选项，通过map遍历filters，为每一个选项赋值。
          this.pointList.map(item => {
            return h("el-option", {
              props: {
                value: item.id,
                label: item.name
              }
            });
          })
        ]
      );
    },
    //选择点位进行筛选事件，重新渲染表格
    searchPoint() {
      this.getListData();
    },
    //选择行为状态进行渲染
    renderStateHeader(h) {
      return h(
        "el-select",
        {
          //el-select实现下拉框
          style: "width:150px",
          class: "normal-top-select",
          on: {
            input: value => {
              //随着下拉框的不同，文字框里的内容改变
              this.stateValue = value;
              change: this.searchState(); // 文字框里的内容 change事件
            }
          },
          props: {
            placeholder: "行为状态",
            value: this.stateValue //文字框的内容取决于这个value
          }
        },
        [
          //下拉框里面填充选项，通过map遍历filters，为每一个选项赋值。
          this.stateList.map(item => {
            return h("el-option", {
              props: {
                value: item.value,
                label: item.name
              }
            });
          })
        ]
      );
    },
    //选择状态进行筛选事件，重新渲染表格
    searchState() {
      this.getListData();
    },
    //图片上传成功的钩子
    handleAvatarSuccess(res, files) {
      this.form.imageUrl = URL.createObjectURL(files.raw);
    },
    //上传图片
    unitUpload(params) {
      var formData = new FormData();
      formData.append("picture", params.file);
      formData.append("uuid", this.$route.query.uuid);
      this.axios
        .post("/admin/third/upload_behavior_picture", formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          this.form.imageUrl = res.data.data.absolute_url;
          this.upload_path = res.data.data.relative_url;
        });
    },
    //限制图片上传的大小
    beforeAvatarUpload(files) {
      const isLt2M = files.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    //限制上传个数
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，如需再次上传，请先移除图片!`
      );
    },
    //移除图片
    handleRemove(files, fileList) {
      this.form.imageUrl = "";
    },
    //移除图片前的钩子
    beforeRemove(files, fileList) {
      return this.$confirm(`确定移除 ${files.name}？`);
    },
    //确认提交数据
    submitData(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          axios
            .post(
              "/admin/third/create_behavior_data",
              qs.stringify({
                project_id: this.projects,
                uuid: this.$route.query.uuid,
                pic_url: this.upload_path,
                camera_id: this.form.point,
                behavior_time: this.form.time,
                behavior_status: this.form.state
              }),
              {
                headers: {
                  "Content-Type":
                    "application/x-www-form-urlencoded; charset=UTF-8"
                }
              }
            )
            .then(
              res => {
                if (res.data.msg === "SUCCESS") {
                  this.dialogFormVisible = false;
                  this.$message({
                    message: "上传成功",
                    type: "success"
                  });
                  this.requestParams.page = 1;
                  this.actionPageChange(this.requestParams.page);
                }
              },
              err => {
                console.log(err);
              }
            );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //清除数据
    clearData(form) {
      this.$refs[form].resetFields();
    },
    //获取时间下拉框数据
    getTimeList() {
      standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "behavior_order_status"
          }
        })
        .then(res => {
          this.filters = res.data.list;
        })
        .catch(error => {
          console.log(error);
        });
    },
    //获取摄像点位下拉框数据
    getPointList() {
      monitorPublicApi
        .getPonitList({
          params: {
            project_id: this.projects,
          }
        })
        .then(res => {
          this.pointList = res.data;
        });
    },
    //摄像点数据过滤
    handleCameraFilter(row) {
      var camera;
      this.pointList.filter(item => {
        if (item.id == row.behavior_camera_id) {
          camera = item.name;
        }
      });
      return camera;
    },
    //获取行为状态下拉框的数据
    getStateList() {
      standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "behavior_status"
          }
        })
        .then(res => {
          this.stateList = res.data.list;
        })
        .catch(error => {
          console.log(error);
        });
    },
    //行为数据过滤
    handleBehaviorFilter(row) {
      var behavior;
      this.stateList.filter(item => {
        if (item.value == row.behavior_status) {
          behavior = item.name;
        }
      });
      return behavior;
    },
    //选择时间
    changeTime(data) {
      if (!data) {
        this.form.time = "";
      } else {
        var stime = new Date(data);
        var y = stime.getFullYear();
        var m = stime.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = stime.getDate();
        d = d < 10 ? "0" + d : d;
        var h = stime.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = stime.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = stime.getSeconds();
        second = second < 10 ? "0" + second : second;
        var start =
          y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
        this.form.time = start;
      }
    },
    //分页
    actionPageChange(page) {
      this.requestParams.page = page;
      this.getListData();
    },
    //获取页面表格数据
    getListData() {
      monitorPublicApi
        .getBehaviorList({
          params: {
            project_id: this.projects,
            behavior_status: this.stateValue,
            behavior_camera_id: this.pointValue,
            order: this.timeValue,
            page: this.requestParams.page
          }
        })
        .then(res => {
          this.actionTable.list = res.data.data;
          this.actionTable.total_count = res.data.total;
        });
    },
    //点击表格行，获取行数据，并展示右侧图片
    getRowData(row) {
      this.pic_url = row.pic_url;
    },
    openApp() {}
  },
  created() {
    this.getTimeList();
    this.getPointList();
    this.getStateList();
    this.getListData();
  }
};
</script>
<style lang="scss" scoped>
.actionMonitor_nav {
  padding: 0 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #d9d9d9;
  height: 60px;

  .titles {
    text-align: left;
    line-height: 60px;
    font-size: 16px;
    color: #1441b3;
  }

  .backScreen {
    text-align: right;
    line-height: 60px;
  }
}

.actionMonitorContent {
  padding: 0 20px;

  .top-btnModule {
    margin-bottom: 20px;
  }

  .mid-tableModule {
    margin-bottom: 20px;
    height: 311px;

    .image-box {
      width: 100%;
      height: 311px;

      img {
        height: 311px;
        display: block;
        width: 100%;
      }
    }
  }
}

//公共样式
.actionMonitor {
  .normal-input {
    width: 200px;
  }

  /deep/ .normal-top-select .el-input__inner {
    border: 0;
    outline: none;
    background: #f5f5f5;
    // padding-right: 0px;
    text-align: right;
  }

  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  /deep/ .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }

  /deep/ .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }

  /deep/ .upload-dialog .el-dialog {
    border-radius: 10px;
  }

  /deep/ .upload-dialog .el-dialog__body {
    padding-bottom: 0px;
  }

  .dialog-footer {
    text-align: center;
  }

  /deep/ .dialog-select {
    width: 220px;
  }
}
</style>